package com.fc2.blog96.nonbirimuchiki.SlideShowClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.util.Log;

public class BluetoothSettingActivity extends Activity {

	//static BluetoothAdapter mBtAdapter;
	//BluetoothManager mBtManager;
	int REQUEST_ENABLE_BLUETOOTH = 0;
	private ArrayAdapter<String> pairedDeviceAdapter;
	private ArrayAdapter<String> nonPairedDeviceAdapter;
	private Set<BluetoothDevice> pairedDevices;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluetoothseting);
        if(!(new File(common.FOLDER_PATH)).exists())
        {
        	(new File(common.FOLDER_PATH)).mkdir();
        	// Copy先の取得
            File cpFile = new File( common.FOLDER_PATH+"/" + "SlideShowServer.lzh" );
            try{

                Resources res = this.getResources();

                InputStream is = res.openRawResource( R.raw.slideshowserver );
                OutputStream os = new FileOutputStream( cpFile );

                byte[] buffer = new byte[ 1024*4 ];    // 1024*4 = DEFAULT BUFFER SIZE
                int r = 0;
                while( -1 != ( r = is.read(buffer)) ){
                    os.write( buffer, 0, r );
                }

                is.close();
                os.close();

            }catch( Exception ex ){

            }
        }

        if(!checkBluetoothSupport())  //bluetoothがサポートされていない
        {
        	showErrorDialog("デバイスエラー","デバイスが対応していません","OK",common.AlertDialogMode.ALERT_DIALOG_MODE_FINISH);
        	finish();
        }
        else OnOffConfirm();  //deviceのON/OFFチェック
    }

    private boolean checkBluetoothSupport()
    {
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        if(adapter.equals(null))
        {
        	return false;
        }
        BluetoothManager.btAdapter = adapter;
        return true;
    }

    private boolean OnOffConfirm()
    {
    	if(BluetoothManager.btAdapter.isEnabled()==false)
    	{
    		Intent BtOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        	startActivityForResult(BtOn, REQUEST_ENABLE_BLUETOOTH);
    	}
    	else
    	{
    		createBluetoothDeviceList();
    		//finish();
    	}
    	return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int ResultCode, Intent date){

    	if(requestCode == REQUEST_ENABLE_BLUETOOTH)
    	{
    		if(ResultCode == Activity.RESULT_OK)
    		{
    			createBluetoothDeviceList();
    		}
    	}
    }

    private void createBluetoothDeviceList()
    {
    	pairedDeviceAdapter = new ArrayAdapter<String>(this, R.layout.rowdata);
        pairedDevices = BluetoothManager.btAdapter.getBondedDevices();
        if(pairedDevices.size() > 0){
        	for(BluetoothDevice device:pairedDevices){
        		pairedDeviceAdapter.add(device.getName() + "\n" + device.getAddress());
        	}
        	ListView deviceList = (ListView)findViewById(R.id.pairedDeviceList);
        	deviceList.setAdapter(pairedDeviceAdapter);

        	deviceList.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> view, View arg1,int pos, long arg3) {
					ListView listView = (ListView) view;
	                String item = (String) listView.getItemAtPosition(pos);
	                Log(item);
	                Iterator ite = pairedDevices.iterator();
	                for(int i=0;i<pos;i++)
	                {
	                	ite.next();
	                }
	                BluetoothManager.btDevice = (BluetoothDevice)ite.next();
	                Intent intent = new Intent(getApplicationContext(), SlideShowClientActivity.class);

	        		startActivity(intent);
	        		finish();
				}
        	});
        }
    }


    private void showErrorDialog(String title,String message,String str,int activemode)
    {
    	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // アラートダイアログのタイトルを設定します
        alertDialogBuilder.setTitle(title);
        // アラートダイアログのメッセージを設定します
        alertDialogBuilder.setMessage(message);
        // アラートダイアログの肯定ボタンがクリックされた時に呼び出されるコールバックリスナーを登録します
        switch(activemode)
        {
        default:
            alertDialogBuilder.setPositiveButton(str,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
            break;
        case common.AlertDialogMode.ALERT_DIALOG_MODE_FINISH:
            alertDialogBuilder.setPositiveButton(str,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
            break;
        }

        // アラートダイアログのキャンセルが可能かどうかを設定します
        alertDialogBuilder.setCancelable(true);
        AlertDialog alertDialog = alertDialogBuilder.create();
        // アラートダイアログを表示します
        alertDialog.show();
    }

    public void Log(String string){
		Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
    }
}